<?php
namespace app\admin\controller;

\think\Loader::import('controller/Controller', \think\Config::get('traits_path') , EXT);

use app\admin\Controller;
use think\Db;
use think\Request;

set_time_limit(0);

class OrderTraveler extends Controller
{
    use \app\admin\traits\controller\Controller;
    // 方法黑名单
    protected static $blacklist = [];

    /**
     * 首页
     * @return mixed
     */
    public function index()
    {

        $data = input();
        $url = '/admin/order_traveler/index_html';
        if ($data){
            foreach ($data as $dk=>$dv){
                if ($dk == $url){
                    unset($data[$dk]);
                }
                if (!empty($dv)){
                    $searchData[$dk] = $dv;
                }
            }
            $searchData['search'] = 'all';
        }else{
            $searchData['search'] = 'all';
        }
        if ($data['remark']){
            $map['ot.remark'] = ['like','%'.$data['remark'].'%'];
        }
        if ($data['sales_id']) {
            $map['o.sales_id'] =array('in',$data['sales_id']) ;
        }
        if($this->request->param("order_id")){
            $map['o.order_id']=array('like',"%{$this->request->param("order_id")}%");
        }
        if($data['booking_people_name']){
            $map['o.booking_people_name'] =array('like',"%{$data['booking_people_name']}%") ;
        }
        if($data['booking_people_phone']){
            $map['o.booking_people_phone'] =array('like',"%{$data['booking_people_phone']}%") ;
        }

        if($this->request->param("name")){
            $map['ot.name']=array('like',"%{$this->request->param("name")}%");
        }

        if($this->request->param("phone")){
            $map['ot.phone']=array('like',"%{$this->request->param("phone")}%");
        }
        if($this->request->param("id_card")){
            $map['ot.id_card']=array('like',"%{$this->request->param("id_card")}%");
        }
        if ($data['sku_id']) {
            $map['o.sku_id'] =array('in',$data['sku_id']) ;
        }
        if($data['order_status']){
            $map['o.order_status'] =$data['order_status'];
        }
        if($data['isrefund']=='0'||$data['isrefund']){
            $map['o.isrefund'] = $data['isrefund'];
        }
        if($data['platform']){
            $map['o.platform'] = $data['platform'];
        }
        if ($data["isallot"]==1) {
            $map['ot.group_id']=array('gt',0);
        }elseif ($data["isallot"]===3){
            $map['ot.group_id']=0;
        }
        if($data['ctime']){
            $map['o.ctime'] = array("between",[strtotime($data['ctime']." 00:00:00"),strtotime($data['ctime']." 23:59:59")]);

        }

        //出行日期
        if ($data['start_time']){
            $map['o.start_time'] = ['=',strtotime($data['start_time'])];
        }


        $listRows = $this->request->param('numPerPage') ?: config("paginate.list_rows");
//        $map['group_id']=0;
        $list = Db::name('OrderTraveler')
        ->alias("ot")
        ->join("order o","ot.oid=o.id",'left')
        ->where($map)
        ->order('ot.oid desc')
        ->paginate($listRows, false, ['query' => $this->request->get()]);
        //获取订单id
        $oids=[];
        foreach ($list as $item){
            $oids[$item['oid']]=true;
        }
        $oids=array_keys($oids);
        $order_travelers=[];
        foreach ($oids as $oid){
             $travelers=Db::name('OrderTraveler')
                ->alias("ot")
                ->join("tp_order o","ot.oid=o.id",'left')
                 ->join("tp_mfw_sku sku" ,"o.sku_id=sku.sku_id","left")
//                ->join("tp_route r","r.id=o.route_id",'left')
                ->where('oid',$oid)
                ->order('ot.oid desc')
                ->field("ot.*,o.title,o.start_time,o.car_form,o.booking_people_name,o.booking_people_phone,o.sales_id,o.order_id,sku.sku_name,o.platform")
                ->select();
            $num = count($travelers);
            if($num==1){
                $travelers[0]['show_single']=true;
                $travelers[0]['show_mian']=false;
                $travelers[0]['show_between']=false;
                $travelers[0]['show_end']=false;
                $order_travelers[]=$travelers[0];
            }else{
                foreach ($travelers as $key=>$traveler){
                    if($key==0){
                        $travelers[$key]['show_single']=false;
                        $travelers[$key]['show_mian']=true;
                        $travelers[$key]['show_between']=false;
                        $travelers[$key]['show_end']=false;
                    }elseif($key+1<$num){
                        $travelers[$key]['show_single']=false;
                        $travelers[$key]['show_mian']=false;
                        $travelers[$key]['show_between']=true;
                        $travelers[$key]['show_end']=false;
                    }elseif($key+1==$num){
                        $travelers[$key]['show_single']=false;
                        $travelers[$key]['show_mian']=false;
                        $travelers[$key]['show_between']=false;
                        $travelers[$key]['show_end']=true;
                    }
                    $order_travelers[]=$travelers[$key];
                }
            }

        }

        // 模板赋值显示
        $platform = Db::name('platform')->select();
        $this->view->assign('platform', $platform);
        $this->view->assign('list', $order_travelers);
        $this->view->assign("count", $list->total());
        $this->view->assign("page", $list->render());
        $this->view->assign('numPerPage', $list->listRows());
        $this->view->assign('searchCondition',$searchData);//搜索条件


        return $this->view->fetch();
    }

    /**
     * 导出数据到excel
     */
    public function export_to_excel()
    {
        $data = input();
        Vendor('PHPExcel.PHPExcel');
        Vendor('PHPExcel.PHPExcel.WorkSheet.Drawing');
        Vendor('PHPExcel.PHPExcel.Writer.Excel2007');
        //实例化
        $export_excel = new \PHPExcel();
        //设置文档属性
        $writer = \PHPExcel_IOFactory::createWriter($export_excel,'Excel2007');
        //设置内容
        $export_sheet = $export_excel->getActiveSheet();
        for ($l = 0; $l < 26; $l++) {
            $letter[] = chr($l+65);
        }
        $countChr = count($letter);
        for ($j = 0; $j < $countChr; $j++) {
            for ($k = 0; $k < $countChr; $k++) {
                $letter[] = $letter[$j].$letter[$k];
            }
        }
        $li_length = count($letter);//设置单元格的宽度
        for ($li=0;$li<$li_length;$li++){
            switch ($letter[$li]){
                case 'A':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(10);break;
                case 'B':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(10);break;
                case 'C':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(15);break;
                case 'D':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(18);break;
                case 'E':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(18);break;
                case 'G':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(5);break;
                case 'H':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(5);break;
                case 'I':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(5);break;
                case 'J':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(5);break;
                case 'K':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(5);break;
                case 'AK':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(10);break;
                default:
                  $export_sheet->getColumnDimension("$letter[$li]")->setWidth(25);
            }
        }
        $tableHeader = ['ID','姓名','手机号码','身份证号码','地址','订单号','分组id','年龄','性别','人员组',
            '包含住宿','是否删除','状态','车辆调整','房间调整','备注','住宿备注','开始时间','结束时间','订单处理状态','订单号','订单状态','是否退款'
            ,'退款状态','旅游路线','金额','标题','退款金额','平台','是否分配','旅游天数','是否分配完成','预订人姓名'
            ,'预订人邮箱','预订人手机号码','预订人微信','预订人备注','预约电话','是否全额退款','用车形式',
            '产品_id','出发时间','sku属性名'];
        $tableLength = count($tableHeader);
        for ($i = 0; $i < $tableLength; $i++){
            $export_sheet->setCellValue("$letter[$i]1","$tableHeader[$i]");
        }
        //搜索条件
        if ($data['remark']){//新增备注搜索
            $map['ot.remark'] = ['like','%'.$data['remark'].'%'];
        }
        if ($data['sales_id']){
            $map['o.sales_id'] =array('in',$data['sales_id']) ;
        }
        if ($data['order_id']){
            $map['o.order_id']=array('like',"%".$data['order_id']."%");
        }
        if ($data['booking_people_name']){
            $map['o.booking_people_name'] =['like','%'.$data['booking_people_name'].'%'];
        }
        if ($data['booking_people_phone']){
            $map['o.booking_people_phone'] =['like','%'.$data['booking_people_phone'].'%'];
        }
        if ($data['name']){
            $map['ot.name']=array('like',"%".$data['name']."%");
        }
        if ($data['phone']){
            $map['ot.phone']=['like','%'.$data['phone'].'%'];
        }
        if ($data['id_card']){
            $map['ot.id_card']=['like','%'.$data['id_card'].'%'];
        }
        if ($data['ctime']){
            $map['o.ctime'] = array("between",[strtotime($data['ctime']." 00:00:00"),strtotime($data['ctime']." 23:59:59")]);
        }
        if ($data['start_time']){
            $map['o.start_time'] = ['=',strtotime($data['start_time'])];
        }
        if ($data['sku_id']){
            $map['o.sku_id'] =array('in',$data['sku_id']);
        }
        if ($data['order_status']){
            $map['o.order_status'] =$data['order_status'];
        }
        if($data['isrefund']=='0'||$data['isrefund']){
            $map['o.isrefund'] = $data['isrefund'];
        }
        if ($data['platform']){
            $map['o.platform'] = $data['platform'];
        }
        if ($data["isallot"]==1) {
            $map['ot.group_id']=array('gt',0);
        }elseif ($data["isallot"]===3){
            $map['ot.group_id']=0;
        }

        $order_field = ['o.order_id,o.order_status','o.isrefund','o.refund_status','o.route_id','o.money','o.title'
            ,'o.refund_money','o.platform','o.status','o.isdelete','o.start_time','o.end_time','o.isallot','o.days'
            ,'o.allot_end','o.booking_people_name','o.booking_people_email','o.booking_people_phone','o.booking_people_wechat','o.booking_people_remark',
            'o.booking_people_phone_area','o.all_refund_flag','o.car_form','o.sales_id','o.ctime','o.sku_id'];
        //查询要填充表格数据
        $list = Db::name('OrderTraveler')
            ->alias("ot")
            ->join("order o","ot.oid=o.id",'left')
            ->where($map)
            ->field('ot.*')
            ->field($order_field)
            ->order('ot.oid desc')
            ->select();
        //还要处理数据
        //查询平台
        $platform = Db::name('platform')->field('id,name,platform_name')->select();
        foreach ($list as $lk=>$lv){
            $list[$lk]['oid'] = empty($lv['oid'])?'':Db::name('order')->where('id',$lv['oid'])->value('order_id');
            $list[$lk]['isdelete'] = empty($lv['isdelete'])?'未删除':'已删除';
            $list[$lk]['start_time'] = empty($lv['start_time']) ? '':date('Y-m-d H:i:s',$lv['start_time']);
            $list[$lk]['end_time'] = empty($lv['end_time']) ? '':date('Y-m-d H:i:s',$lv['end_time']);
            $list[$lk]['age'] = empty($lv['age']) ? '':$lv['age'].'岁';
            $list[$lk]['ctime'] = empty($lv['ctime']) ? '':date('Y-m-d H:i:s',$lv['ctime']);
            //订单状态
            switch ($lv['order_status']){
                case 'issue': $list[$lk]['order_status'] = '已出单'; break;
                case 'pay_for': $list[$lk]['order_status'] = '待付款'; break;
                case 'pending': $list[$lk]['order_status'] = '待出单'; break;
                case 'finish': $list[$lk]['order_status'] = '已完成'; break;
                case 'close': $list[$lk]['order_status'] = '已关闭'; break;
            }
            //订单状态
            switch ($lv['status']){
                case 1: $list[$lk]['status'] = '启用'; break;
                case 0: $list[$lk]['status'] = '禁用'; break;
            }
            $list[$lk]['money'] = empty($lv['money']) ? '':$lv['money'].'￥';
            $list[$lk]['refund_money'] = empty($lv['refund_money']) ? '':$lv['refund_money'].'￥';//退款金额
            //是否退款
            $list[$lk]['isrefund'] = empty($lv['isrefund']) ? '不退款':'是退款';
//            $list[$lk]['platform'] = ($lv['platform']=='mfw') ? '马蜂窝':'手动添加';
            $list[$lk]['isallot'] = ($lv['isallot']==1) ? '已分配':'未分配';
            $list[$lk]['allot_end'] = ($lv['allot_end']==1) ? '是分配完成':'未分配完成';
            foreach ($platform as $pfk=>$pfv){
                if ($pfv['platform_name'] == $lv['platform']){
                    $list[$lk]['platform'] = $pfv['name'];
                }
            }
            if (empty($list[$lk]['platform'])){
                $list[$lk]['platform'] = '';
            }
            //退款状态
            switch ($lv['refund_status']){
                case 'check': $list[$lk]['refund_status'] = '审核中'; break;
                case 'refunding': $list[$lk]['refund_status'] = '退款中'; break;
                case 'refunded': $list[$lk]['refund_status'] = '已退款'; break;
                case 'rejected': $list[$lk]['refund_status'] = '拒绝退款'; break;
            }
            //路线
            $list[$lk]['route_id'] = empty($lv['route_id']) ? '':Db::name('route')->where('id',$lv['route_id'])->value('title');
            if ($lv['platform']=='mfw'){
                $sku_data = Db::name('mfw_sku')->where('sku_id',$lv['sku_id'])->field('sales_name,sku_name')->find();
                $list[$lk]['sku_id'] = $sku_data['sku_name'];
                $list[$lk]['sales_id'] = $sku_data['sku_name'];
            }
        }
//        dump($list[0]);die('输出数据');
        //定义table键
        if (!empty($list)){
            $tableKey = array_keys($list[0]);
            //填充表格信息
            $tableKeyLength = count($tableKey);
            foreach ($list as $tk=>$tv){
                $tk += 2;
                for ($i = 0; $i < $tableKeyLength; $i++){
                    $export_sheet->setCellValue("$letter[$i]".$tk,$tv[$tableKey[$i]]);
                }
            }
        }
        $fileName = date('YmdHis',time())."订单管理-全部旅客数据.xls";
        $fileName = iconv('utf-8','gb2312',$fileName);
        ob_end_clean();
        header('Content-Type:application/force-download');
        header('Content-Type:application/octet-stream');
        header('Content-Type:application/download');
        header('Content-Disposition:inline;filename='.$fileName);
        header('Content-Transfer-Encoding:binary');
        header('Cache-Control:must-revalidate,post-check=0');
        header('Pragma:no-cache');
        $writer->save('php://output');
        exit();
    }


    /**
     * 已有分组
     * @return mixed
     */
    public function in_group()
    {

        $data = input();
        if ($data['sales_id']) {
            $map['o.sales_id'] =array('in',$data['sales_id']) ;
        }
        if($this->request->param("order_id")){
            $map['o.order_id']=array('like',"%{$this->request->param("order_id")}%");
        }
        if ($data['remark']){//新增备注搜索
            $map['ot.remark'] = ['like','%'.$data['remark'].'%'];
        }
        if($data['booking_people_name']){
            $map['o.booking_people_name'] =array('like',"%{$data['booking_people_name']}%") ;
        }
        if($data['booking_people_phone']){
            $map['o.booking_people_phone'] =array('like',"%{$data['booking_people_phone']}%") ;
        }

        if($this->request->param("name")){
            $map['ot.name']=array('like',"%{$this->request->param("name")}%");
        }

        if($this->request->param("phone")){
            $map['ot.phone']=array('like',"%{$this->request->param("phone")}%");
        }
        if($this->request->param("id_card")){
            $map['ot.id_card']=array('like',"%{$this->request->param("id_card")}%");
        }
        if ($data['sku_id']) {
            $map['o.sku_id'] =array('in',$data['sku_id']) ;
        }
        if($data['order_status']){
            $map['o.order_status'] =$data['order_status'];
        }
        if($data['isrefund']=='0'||$data['isrefund']){
            $map['o.isrefund'] = $data['isrefund'];
        }
        if($data['platform']){
            $map['o.platform'] = $data['platform'];
        }
        $map['ot.group_id']=array('gt',0);
        if ($data['date1']) {
            $date1 = strtotime($data['date1']);
        }
        if ($data['date2']) {
            $date2 =  strtotime($data['date2']);
        }

        if ($date1 && $date2) {
            if ($date1 < $date2) {
                $start = $date1;
                $end = $date2;
            } else {
                $start = $date2;
                $end = $date1;
            }
        } else if ($date1) {
            $start = $date1;
        } else if ($date2) {
            $start = $date2;
        }
        if ($start && $end) {
            $map['o.start_time'] = array('between',array($start,$end));
            $this->request->get(array("date1" => date("Y-m-d", $start)));
            $this->request->get(array("date2" => date("Y-m-d", $end)));
        } else if($start){
//            $map['o.start_time'] = array("egt",$start);
            $map['o.start_time'] = array("between",[strtotime($data['start_time']." 00:00:00"),strtotime($data['start_time']." 23:59:59")]);
            $this->request->get(array("date1" => date("Y-m-d", $start)));
        }
        if($data['ctime']){
            $map['o.ctime'] = array("between",[strtotime($data['ctime']." 00:00:00"),strtotime($data['ctime']." 23:59:59")]);

        }
        //出行日期
        if ($data['start_time']){
            $map['o.start_time'] = ['=',strtotime($data['start_time'])];
        }

        $listRows = $this->request->param('numPerPage') ?: config("paginate.list_rows");
//        $map['group_id']=0;
        $list = Db::name('OrderTraveler')
            ->alias("ot")
            ->join("order o","ot.oid=o.id",'left')
            ->where($map)
            ->order('ot.oid desc')
            ->paginate($listRows, false, ['query' => $this->request->get()]);
        //获取订单id
        $oids=[];
        foreach ($list as $item){
            $oids[$item['oid']]=true;
        }
        $oids=array_keys($oids);
        $order_travelers=[];
        foreach ($oids as $oid){
            $travelers=Db::name('OrderTraveler')
                ->alias("ot")
                ->join("tp_order o","ot.oid=o.id",'left')
                ->join("tp_mfw_sku sku" ,"o.sku_id=sku.sku_id","left")
//                ->join("tp_route r","r.id=o.route_id",'left')
                ->where('oid',$oid)
                ->order('ot.oid desc')
                ->field("ot.*,o.title,o.start_time,o.car_form,o.booking_people_name,o.booking_people_phone,o.sales_id,o.order_id,sku.sku_name,o.platform")
                ->select();
            $num = count($travelers);
            if($num==1){
                $travelers[0]['show_single']=true;
                $travelers[0]['show_mian']=false;
                $travelers[0]['show_between']=false;
                $travelers[0]['show_end']=false;
                $order_travelers[]=$travelers[0];
            }else{
                foreach ($travelers as $key=>$traveler){
                    if($key==0){
                        $travelers[$key]['show_single']=false;
                        $travelers[$key]['show_mian']=true;
                        $travelers[$key]['show_between']=false;
                        $travelers[$key]['show_end']=false;
                    }elseif($key+1<$num){
                        $travelers[$key]['show_single']=false;
                        $travelers[$key]['show_mian']=false;
                        $travelers[$key]['show_between']=true;
                        $travelers[$key]['show_end']=false;
                    }elseif($key+1==$num){
                        $travelers[$key]['show_single']=false;
                        $travelers[$key]['show_mian']=false;
                        $travelers[$key]['show_between']=false;
                        $travelers[$key]['show_end']=true;
                    }
                    $order_travelers[]=$travelers[$key];
                }
            }

        }

//        dump($order_travelers);
        // 模板赋值显示
        $platform = Db::name('platform')->select();
        $this->view->assign('Request.param.ctime', $data);
        $this->view->assign('$Request.param.start_time', $data);
        $this->view->assign('platform', $platform);
        $this->view->assign('list', $order_travelers);
        $this->view->assign("count", $list->total());
        $this->view->assign("page", $list->render());
        $this->view->assign('numPerPage', $list->listRows());


        return $this->view->fetch();
    }

    /**
     * 旅客分配
     * @return mixed
     */
    public function dispatch_group(Request $request)
    {

        $data = input();
        if ($data['sales_id']) {
            $map['o.sales_id'] =array('in',$data['sales_id']) ;
        }
        if($this->request->param("order_id")){
            $map['o.order_id']=array('like',"%{$this->request->param("order_id")}%");
        }
        if($data['booking_people_name']){
            $map['o.booking_people_name'] =array('like',"%{$data['booking_people_name']}%") ;
        }
        if ($data['remark']){//新增备注搜索
        $map['ot.remark'] = ['like','%'.$data['remark'].'%'];
         }
        if($data['booking_people_phone']){
            $map['o.booking_people_phone'] =array('like',"%{$data['booking_people_phone']}%") ;
        }

        if($this->request->param("name")){
            $map['ot.name']=array('like',"%{$this->request->param("name")}%");
        }

        if($this->request->param("phone")){
            $map['ot.phone']=array('like',"%{$this->request->param("phone")}%");
        }
        if($this->request->param("id_card")){
            $map['ot.id_card']=array('like',"%{$this->request->param("id_card")}%");
        }
        if ($data['sku_id']) {
            $map['o.sku_id'] =array('in',$data['sku_id']) ;
        }
        if($data['order_status']){
            $map['o.order_status'] =$data['order_status'];
        }
        if($data['isrefund']=='0'||$data['isrefund']){
            $map['o.isrefund'] = $data['isrefund'];
        }
        if($data['platform']){
            $map['o.platform'] = $data['platform'];
        }
        $map['o.order_status'] =array('not in',array('close','finish'));
        if ($this->request->param("isallot")) {
            $map['ot.group_id']=array('gt',0);
        }elseif ($this->request->param("isallot")==="0"){
            $map['ot.group_id']=0;
        }
        if ($data['date1']) {
            $date1 = strtotime($data['date1']);
        }
        if ($data['date2']) {
            $date2 =  strtotime($data['date2']);
        }

        if ($date1 && $date2) {
            if ($date1 < $date2) {
                $start = $date1;
                $end = $date2;
            } else {
                $start = $date2;
                $end = $date1;
            }
        } else if ($date1) {
            $start = $date1;
        } else if ($date2) {
            $start = $date2;
        }
        if ($start && $end) {
            $map['o.start_time'] = array('between',array($start,$end));
            $this->request->get(array("date1" => date("Y-m-d", $start)));
            $this->request->get(array("date2" => date("Y-m-d", $end)));
        } else if($start){
    //            $map['o.start_time'] = array("egt",$start);
            $map['o.start_time'] = array("between",[strtotime($data['start_time']." 00:00:00"),strtotime($data['start_time']." 23:59:59")]);
            $this->request->get(array("date1" => date("Y-m-d", $start)));
        }
        if($data['ctime']){
            $map['o.ctime'] = array("between",[strtotime($data['ctime']." 00:00:00"),strtotime($data['ctime']." 23:59:59")]);

        }
        //出行日期
        if ($data['start_time']){
            $map['o.start_time'] = ['=',strtotime($data['start_time'])];
        }


        $listRows = $this->request->param('numPerPage') ?: config("paginate.list_rows");
        $map['group_id']=0;
        $list = Db::name('OrderTraveler')
            ->alias("ot")
            ->join("order o","ot.oid=o.id",'left')
            ->where($map)
            ->order('ot.oid desc')
            ->paginate($listRows, false, ['query' => $this->request->get()]);

        //获取订单id
        $oids=[];
        foreach ($list as $item){
            $oids[$item['oid']]=true;
        }
        $oids=array_keys($oids);
        $order_travelers=[];
        foreach ($oids as $oid){
            $travelers=Db::name('OrderTraveler')
                ->alias("ot")
                ->join("tp_order o","ot.oid=o.id",'left')
                ->join("tp_mfw_sku sku" ,"o.sku_id=sku.sku_id","left")
    //                ->join("tp_route r","r.id=o.route_id",'left')
                ->where('ot.oid',$oid)
                ->where('ot.group_id',0)
                ->order('ot.oid desc')
                ->field("ot.*,o.title,o.start_time,o.car_form,o.booking_people_name,o.booking_people_phone,o.sales_id,o.order_id,sku.sku_name,o.platform")
                ->select();
            $num = count($travelers);
            if($num==1){
                $travelers[0]['show_single']=true;
                $travelers[0]['show_mian']=false;
                $travelers[0]['show_between']=false;
                $travelers[0]['show_end']=false;
                $order_travelers[]=$travelers[0];
            }else{
                foreach ($travelers as $key=>$traveler){
                    if($key==0){
                        $travelers[$key]['show_single']=false;
                        $travelers[$key]['show_mian']=true;
                        $travelers[$key]['show_between']=false;
                        $travelers[$key]['show_end']=false;
                    }elseif($key+1<$num){
                        $travelers[$key]['show_single']=false;
                        $travelers[$key]['show_mian']=false;
                        $travelers[$key]['show_between']=true;
                        $travelers[$key]['show_end']=false;
                    }elseif($key+1==$num){
                        $travelers[$key]['show_single']=false;
                        $travelers[$key]['show_mian']=false;
                        $travelers[$key]['show_between']=false;
                        $travelers[$key]['show_end']=true;
                    }
                    $order_travelers[]=$travelers[$key];
                }
            }

        }

    //        dump($order_travelers);
        // 模板赋值显示
        $platform = Db::name('platform')->select();
        $this->view->assign('Request.param.ctime', $data);
        $this->view->assign('$Request.param.start_time', $data);
        $this->view->assign('platform', $platform);
        $this->view->assign('list', $order_travelers);
        $this->view->assign("count", $list->total());
        $this->view->assign("page", $list->render());
        $this->view->assign('numPerPage', $list->listRows());
//        return $this->view->fetch(');

        if ($request->isAjax()){
//            dump('ajax提交');
            $this->view->assign('refresh',1);
            return $this->view->fetch('ajaxpage');
        }else{
            return $this->view->fetch('dispatch_group');
        }
    }

    /**
     * 司机分配
     * @return mixed
     */
    public function driver(Request $request)
    {
        if ($request->isPost()){
            $postData = $request->post();
        }else{ // 获取司机数据
            $data = input();
            $driverUserId = [];
            if (!empty($data['driver_user_id'])){
                $driverUserId = explode(',',$data['driver_user_id']); // 已选择的司机用户id
                if (!empty($driverUserId)){
                    foreach ($driverUserId as $key=>$value){
                        if (empty($value)){
                            unset($driverUserId[$key]);
                        }
                    }
                    $map['d.user_id'] = ['not in',$driverUserId];
                }
            }
            // 查询条件
            $driverUserIds = ''; // 查询司机用户id
            if($data['realname']){
                $adminUser = Db::name('admin_user')->where('realname','like',"%{$data['realname']}%")->select();
                if ($adminUser){
                    $userIds = '';
                    foreach ($adminUser as $index33 => $item33) {
                        $userIds .= $item33['id'].',';
                    }
                    $driverUserIds =  rtrim($userIds,',');
                }
            }
            if($data['mobile']){
                $adminUser = Db::name('admin_user')->where('account','like',"%{$data['mobile']}%")->select();
                if ($adminUser){
                    $userIds = '';
                    foreach ($adminUser as $index44 => $item44) {
                        $userIds .= $item44['id'].',';
                    }
                    if (empty($driverUserIds)){
                        $driverUserIds =  rtrim($userIds,',');
                    }else{
                        $userIds = explode(',',rtrim($userIds,','));
                        $driverUserIds = explode(',',$driverUserIds);
                        foreach ($driverUserIds as $keys=>$val){
                            if (!in_array($val,$userIds)){
                                unset($driverUserIds[$keys]); // 删除不在这里的司机
                            }
                        }
                        $driverUserIds = empty($driverUserIds)? '' : implode(',',$driverUserIds); // 转换成字符串
                    }
                }
            }
            if($data['seats']){
                $map['d.seats']=$data['seats'];
            }
            if($data['car_type']){
                $map['d.car_type']=array('like',"%{$data['car_type']}%");
            }
            if($data['car_model']){
                $map['d.car_model']=array('like',"%{$data['car_model']}%");
            }
            if($data['car_brand']){
                $map['d.car_brand']=array('like',"%{$data['car_brand']}%");
            }
            if($data['driver_rank_id']){
                if ($data['driver_rank_id'] == 5){
                    $map['d.driver_rank_id']=0;
                }else{
                    $map['d.driver_rank_id']=$data['driver_rank_id'];
                }
            }
            if ($data['nationality']){
                $map['d.nationality'] = ['like', "%{$data['nationality']}%"];
            }

            if($data['tag']){
                $map['d.tag']=array('like',"%{$data['tag']}%");
            }
            $map['d.isagree'] = 1;
            $map['d.ischeck'] = 1;
            $map['d.isdelete']=0;
            $map['d.inservice']=0; // 不在服务中
            // 查询所有不在服务的司机
            $outOfServiceDrivers = Db::name('driver')->alias('d')
                ->where($map)
                ->select();
            if ($outOfServiceDrivers){
                $out['dispatch_group_status'] = ['in','sendorders,proceed'];
                foreach ($outOfServiceDrivers as $index => $outOfServiceDriver) {
                    $outData = Db::name('dispatch_traveler_group')->where($out)->where('driver_user_id',$outOfServiceDriver['user_id'])->select();
                    if (empty($outData)){
                        $outData = [];
                    }
                    $outOfServiceDrivers[$index]['dispatchOrder'] = $outData;
                    // 查找司机的用户信息
                    $driverUser = Db::name('admin_user')->where('id',$outOfServiceDriver['user_id'])->find(); // 司机用户信息
                    $outOfServiceDrivers[$index]['phone'] = empty($driverUser['mobile']) ? '用户为填手机号码' : $driverUser['mobile'];
                    $outOfServiceDrivers[$index]['realname'] = empty($driverUser['realname']) ? '用户为填姓名' : $driverUser['realname'];
                    // 整理司机的车辆信息
                    $articName = Db::name('arctic')->where('id',$outOfServiceDriver['arctic_id'])->value('name'); // 查找车型名字
                    if (!empty($articName)){
                        $outOfServiceDrivers[$index]['arctic'] = $articName;
                    }else{
                        $outOfServiceDrivers[$index]['arctic'] = empty($outOfServiceDriver['car_type']) ? '未填写车型' : $outOfServiceDriver['car_type'];
                    }
                    $carModelName = Db::name('car_model')->where('id',$outOfServiceDriver['car_model_id'])->value('car_model'); // 查找汽车型号名字
                    if (!empty($carModelName)){
                        $outOfServiceDrivers[$index]['car_model'] = $carModelName;
                    }else{
                        $outOfServiceDrivers[$index]['car_model'] = empty($outOfServiceDriver['car_model']) ? '未填写汽车型号' : $outOfServiceDriver['car_model'];
                    }
                    $carBrandName = Db::name('car_brand')->where('id',$outOfServiceDriver['car_brand_id'])->value('brand_name'); // 查找车辆品牌名字
                    if (!empty($carBrandName)){
                        $outOfServiceDrivers[$index]['brand_name'] = $carBrandName;
                    }else{
                        $outOfServiceDrivers[$index]['brand_name'] = empty($outOfServiceDriver['car_brand']) ? '未填写车辆品牌' : $outOfServiceDriver['car_brand'];
                    }
                }
            }
            // 过滤不在条件的司机
            if (!empty($driverUserIds)){
                foreach ($outOfServiceDrivers as $index77 => $outOfServiceDriver77) {
                    if (!in_array($outOfServiceDriver77['user_id'],explode(',',$driverUserIds))){
                        unset($outOfServiceDrivers[$index77]);
                    }
                }
            }
            $map['d.inservice']=1; // 服务中
            // 查询所有在服务的司机
            $driverInService = Db::name('driver')->alias('d')
                ->where($map)
                ->order('d.user_id','desc')
                ->select();
            if ($driverInService){
                $in['dispatch_group_status'] = ['in', 'sendorders,proceed']; // 进行中或派单中
                foreach ($driverInService as $index01 => $item01) {
                    $inData = Db::name('dispatch_traveler_group')->where($in)->where('driver_user_id',$item01['user_id'])->select();
                    if (empty($inData)){
                        $inData = [];
                    }
                    $driverInService[$index01]['dispatchOrder'] = $inData;
                    // 查找司机的用户信息
                    $driverUser = Db::name('admin_user')->where('id',$item01['user_id'])->find(); // 司机用户信息
                    $driverInService[$index01]['phone'] = empty($driverUser['mobile']) ? '用户为填手机号码' : $driverUser['mobile'];
                    $driverInService[$index01]['realname'] = empty($driverUser['realname']) ? '用户为填姓名' : $driverUser['realname'];
                    // 整理司机的车辆信息
                    $articName = Db::name('arctic')->where('id',$item01['arctic_id'])->value('name'); // 查找车型名字
                    if (!empty($articName)){
                        $driverInService[$index01]['arctic'] = $articName;
                    }else{
                        $driverInService[$index01]['arctic'] = empty($item01['car_type']) ? '未填写车型' : $item01['car_type'];
                    }
                    $carModelName = Db::name('car_model')->where('id',$item01['car_model_id'])->value('car_model'); // 查找汽车型号名字
                    if (!empty($carModelName)){
                        $driverInService[$index01]['car_model'] = $carModelName;
                    }else{
                        $driverInService[$index01]['car_model'] = empty($item01['car_model']) ? '未填写汽车型号' : $item01['car_model'];
                    }
                    $carBrandName = Db::name('car_brand')->where('id',$item01['car_brand_id'])->value('brand_name'); // 查找车辆品牌名字
                    if (!empty($carBrandName)){
                        $driverInService[$index01]['brand_name'] = $carBrandName;
                    }else{
                        $driverInService[$index01]['brand_name'] = empty($item01['car_brand']) ? '未填写车辆品牌' : $item01['car_brand'];
                    }
                }
            }
            // 过滤不在条件的司机
            if (!empty($driverUserIds)){
                foreach ($driverInService as $index78 => $value78) {
                    if (!in_array($value78['user_id'],explode(',',$driverUserIds))){
                        unset($driverInService[$index78]);
                    }
                }
            }
            // 查找所有司机标签
            $map_tags['isdelete']=0;
            $map_tags['status']=1;
            $driver_tags=Db::name('driver_tag')
                ->where($map_tags)
                ->select();
            // 查询所有司机的等级
            $ranks=Db::name('driver_rank')->select();
            // 查找当前的订单
            $order = Db::name('order')->where('id',"in",$data['order_id'])->find();
            $this->view->assign('driver_tags',$driver_tags);
            $this->view->assign('ranks',$ranks);
            $this->view->assign('order',$order);
            $this->view->assign('driver_user_id',$data['driver_user_id']);
            $this->view->assign('outOfServiceDrivers',$outOfServiceDrivers);
            $this->view->assign('driverInService',$driverInService);
            return $this->view->fetch();
        }
    }

    /**
     * 添加分组
     * @return mixed
     */
    public function add_group()
    {
        $input=input();

        $groups=$input['groups'];
        $group_fee = $input['driver_fee'];
        // 验证数据
        $groupData = $input['groups'];
        $leaveData = [];
        if (!empty($groupData) && is_array($groupData)){
            foreach ($groupData as $index => $groupDatum) {
                if (empty($groupDatum['driver_user_id'])){
                    return ajax_return_adv_error('未选择司机');
                }
                // 查询司机的请假信息
                $leaveData[$groupDatum['driver_user_id']] = Db::name('leave')->where('user_id',$groupDatum['driver_user_id'])->select(); // 所有请假列表where user_id=12312
            }
        }
        // 启动事务
        Db::startTrans();
        try{
            foreach ($groups as $val){
		$arr = [];
                foreach ($val['traveler_id'] as $gk => $gv){
                    $oid = Db::name('order_traveler')->where('id',$gv)->value('oid');
                    $arr[$oid] = true;
                }
                $arrs = array_keys($arr);
                $ck_t = [];
                foreach ($arrs as $kk => $vv){
                    $route_id = Db::name('order')->where('id',$vv)->value('route_id');
                    $ck_t[$route_id] = true;
                }
                $route_ids = array_keys($ck_t);
                if(count($route_ids)>1){
                    Db::rollback();
                    return ajax_return_error("旅客订单路线不一致");
                }

                $driver_user_id=$val['driver_user_id'];
                $frist_traveler_id=$val['traveler_id'][0];
                $frist_oid=Db::name('order_traveler')->where('id',$frist_traveler_id)->value('oid'); // 从订单旅客查找订单id
                $order=Db::name('order')->where('id',$frist_oid)->find();
                $group['title']=$order['title'];
                $group['driver_fee'] = $group_fee;
                $group['num']=count($val['traveler_id']);
                $group['go_date']=$order['start_time'];
                $group['end_date']=$order['end_time']; // 订单结束时间
                $group['traveler_ids']=$val['traveler_id'];
                $model_group=new \app\common\model\DispatchTravelerGroup();
                $group_id=$model_group->insert_group($group); // 添加分组
                if(!$group_id){
                    Db::rollback();
                    return ajax_return_error("旅客分配冲突或者已分配");
                }
                // 校对时间不能为空
                if (empty($order['start_time'])){
                    Db::rollback();
                    return ajax_return_adv_error('订单缺失开始时间，无法进行时间冲突校对');
                }
                if (empty($order['end_time'])){
                    Db::rollback();
                    return ajax_return_adv_error('订单缺失结束时间，无法进行时间冲突校对');
                }
                //分配司机
                //判断订单是否异常
                $group_order_ids=Db::name('dispatch_traveler')
                    ->where('group_id',$group_id)
                    ->group("oid")
                    ->column("oid");
                $exceptional_orders= Db::name('exceptional_order')->where('oid','in',$group_order_ids)->where('solve',false)->find();
                if($exceptional_orders){
                    // 回滚事务
                    Db::rollback();
                    return ajax_return_error("订单id为{$exceptional_orders['oid']}的订单存在异常状态");
                }
                $dispatch_traveler_group=Db::name('dispatch_traveler_group')->where('id',$group_id)->find();
                // 检测某段时间司机是否有空闲
                // ①分配的订单不能在司机的请假时间
                // 求出订单的时间
                $tian = round(($order['end_time']-$order['start_time'])/3600/24);
                // 当前的入住日期
                $check_in_date = date('Y-m-d',$order['start_time']);
                // 把入住日期与退房日期的相差天数
                $date = [$check_in_date];
                logs('cha',$date);
                for ($i=1; $i<= $tian; $i++){
                    array_push($date,date("Y-m-d",strtotime("+{$i} day",strtotime("{$check_in_date}"))));//添加的
                }
                if (!empty($order['end_time']) && !empty($order['start_time'])){
                    if ($date){
                        // 查询司机所有的请假时间
                        $driverLeave = [];
                        if (!empty($leaveData)){
                            foreach ($leaveData as $index04 => $leaveDatum) {
                                if ($index04 == $driver_user_id){
                                    $driverLeave = $leaveDatum;
                                }
                            }
                        }
                        foreach ($date as $indexdate => $dateItem) {
                            if (!empty($driverLeave)){
                                foreach ($driverLeave as $index87 => $leaveItem) {
                                    if ($leaveItem['start_time'] <= $dateItem && $leaveItem['end_time'] >= $dateItem){
                                        Db::rollback();
                                        $start_time = empty($order['start_time'])? '未填写开始时间': date('Y-m-d',$order['start_time']);
                                        $end_time = empty($order['end_time'])? '未填写结束时间': date('Y-m-d',$order['end_time']);
                                        return ajax_return_adv_error("用户id为:{$driver_user_id}的司机，请假时间为:{$leaveItem['start_time']}至{$leaveItem['end_time']},与id为{$frist_oid}的订单的时间:{$start_time}-{$end_time},出现冲突");
                                    }
                                }
                            }
                        }
                    }
                }

                // ②不能与司机其他的派单时间存在冲突
                if ($date){
                    $status['dispatch_group_status'] = ['in','sendorders,proceed'];
                    foreach ($date as $index99 => $item99) {
                        $driverDispatch = Db::name('dispatch_traveler_group')
                                            ->where($status)
                                            ->where('go_date','<=',strtotime($item99))
                                            ->where('end_date','>=',strtotime($item99))
                                            ->where('id','not in',$group_id)
                                            ->where('driver_user_id',$driver_user_id)
                                            ->find();
                        if ($driverDispatch){
                            Db::rollback(); // 回滚事务
                            $go_date = empty($driverDispatch['go_date'])? '未填写开始时间': date('Y-m-d',$driverDispatch['go_date']);
                            $end_date = empty($driverDispatch['end_date'])? '未填写结束时间': date('Y-m-d',$driverDispatch['end_date']);
                            $start_time = empty($order['start_time'])? '未填写开始时间': date('Y-m-d',$order['start_time']);
                            $end_time = empty($order['end_time'])? '未填写结束时间': date('Y-m-d',$order['end_time']);
                            return ajax_return_adv_error("用户id为:{$driver_user_id}的司机，派单id为:{$driverDispatch['id']},时间为:{$go_date}至{$end_date},与id为{$frist_oid}的订单的时间:{$start_time}-{$end_time},出现冲突");
                        }
                    }
                }
                //判断司机是否已经在服务
//                $driver=Db::name("driver")->where('user_id',$driver_user_id)->find();
//                if($driver['inservice']){
//                    // 回滚事务
//                    Db::rollback();
//                    return ajax_return_error("用户id为{$driver_user_id}的司机已经分配");
//                }
                if($dispatch_traveler_group['dispatch_group_status']=='undistributed'||!$dispatch_traveler_group['dispatch_group_status']) {
                    $update['driver_user_id']=$driver_user_id;
                    $update['dispatch_group_status']='sendorders';
                    $update['driver_confirm']=false;
                    $update['isreject']=false;
                    $update['dispatch_time']=NOW_TIME;
 		            $update['route_id'] = $route_ids[0];
                    $update['oid'] =implode(",", $group_order_ids);
                    logs("dispatch_traveler_group_update",$update);
                    Db::name('dispatch_traveler_group')->where('id',$group_id)->update($update);

                    $group = Db::name('dispatch_traveler_group')
                        ->where('id', $group_id)
                        ->find();
                    if ($group['dispatch_group_status'] == 'receiving') {
                        return ajax_return_error('订单已处理');
                    }

                    $update['dispatch_group_status'] = 'receiving';
                    $update['driver_confirm'] = true;
                    $update['receiving_time'] = NOW_TIME;

                    $re = Db::name('dispatch_traveler_group')
                        ->where('id', $group_id)
                        ->update($update);

                    //如果不是接机订单
                    if ($group['is_pickup'] != '1') {
                        if ($re) {
                            // 司机接受派单，同步住宿派单
                            $group_ids = $group_id; // 派单id
                            // 从订单旅客表获取派单旅客数据,并且有住宿要求的旅客
                            $groupTravel = Db::name('order_traveler')->where('group_id', $group_ids)->where('isaccommodation', '包含住宿')->select();
                            //  查询派单数据
                            $groupInfo = Db::name('dispatch_traveler_group')->where('id', $group_ids)->find();
                            // 查找司机信息
                            $driver = Db::name('driver')->where('user_id', $groupInfo['driver_user_id'])->find();
                            if ($groupTravel && empty($group['reverse_id'])) {
                                // 同步住宿派单
//                                $insert = [
//                                    'driver_id' => $driver['id'],
//                                    'driver_user_id' => $groupInfo['driver_user_id'],
//                                    'number_of_guests' => count($groupTravel),
//                                    'departure_date' => $groupInfo['go_date'],
//                                    'finish_date' => $groupInfo['end_date'],
//                                    'group_id' => $group_id,
//                                    'car_form' => $groupInfo['car_form'],
//                                    'create_time' => time(),
//                                ];
//                                // 添加到表里
//                                $addId = Db::name('portion_traveler')->strict(false)->insertGetId($insert);

                                //获取订单ids
                                $order_ids = Db::name('order_traveler')->group('oid')->where('group_id', $group_ids)->field('id,oid,group_id')->select();

                                //更改订单状态
                                if (count($order_ids) > 1) {
                                    // order_status issue已出单
                                    // dispose_status normal_travel:正常出行
                                    $update['order_status'] = 'issue';
                                    $update['dispose_status'] = 'normal_travel';
                                    foreach ($order_ids as $ok => $ov) {
                                        Db::name('order')->strict(false)->where('id', $ov['oid'])->update($update);
                                    }
                                }

//                                logs('paidan', $addId);
                            }
                             Db::name("driver")->where('user_id',$driver_user_id)->update(array('inservice'=>1));
                            if ($update['driver_user_id']) {

                                set_info($update['driver_user_id'], '订单分配', "分配成功，你有新的订单,订单编号为:{$group_id}", 'dispatch_traveler_group', array('dispatch_traveler_group_id' => $group_id));

                                // 查找该司机的手机号码
                                $mobile = Db::name('admin_user')->where('id',$update['driver_user_id'])->value('mobile');
                                if ($mobile){
                                    $ret = send_message($mobile,"分配订单成功,您有新的订单,订单编号为:{$group_id}");
                                    logs('paidan',$ret);
                                }

                            }else{
                                // 回滚事务
                                Db::rollback();
                                return ajax_return_error('未分配司导');
                            }
//                            $this->accept($group_id);
                            // 提交事务
                            Db::commit();
                            return ajax_return_adv('接单成功');
                        } else {
                            return ajax_return_error('不存在或未填写信息');
                        }
                    } else {  //如果是接机订单
                        //接机单不需要同步住宿
//                        $this->accept($group_id);
                        // 提交事务
                        Db::commit();
                        return ajax_return_adv('接单成功');
                    }
//                    return json(['aaa' => $group]);

                }else{
                    // 回滚事务
                    Db::rollback();
                    return ajax_return_error('已经分配');
                }
            }
            // 提交事务
            Db::commit();
            return ajax_return_adv();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ajax_return_error($e->getMessage());
        }
    }
    /**
     * 接单
     * @return mixed
     */
    public function accept($group_id)
    {
        //获取数据
//        $data = input();
        $data['group_id']=$group_id;
        $group = Db::name('dispatch_traveler_group')
            ->where('id', $data['group_id'])
            ->find();
//        return json(['datas' => $group]);
        //select * from dispatch_traveler_group where id = group_id
        if ($group['dispatch_group_status'] == 'receiving') {
            return ajax_return_error('订单已处理');
        }

        $update['dispatch_group_status'] = 'receiving';
        $update['driver_confirm'] = true;
        $update['receiving_time'] = NOW_TIME;

        $re = Db::name('dispatch_traveler_group')
            ->where('id', $data['group_id'])
            ->update($update);

        //如果不是接机订单
        if ($group['is_pickup'] != '1') {
            if ($re) {
                // 司机接受派单，同步住宿派单
                $group_id = $data['group_id']; // 派单id
                // 从订单旅客表获取派单旅客数据,并且有住宿要求的旅客
                $groupTravel = Db::name('order_traveler')->where('group_id', $group_id)->where('isaccommodation', '包含住宿')->select();
                //  查询派单数据
                $groupInfo = Db::name('dispatch_traveler_group')->where('id', $group_id)->find();
                // 查找司机信息
                $driver = Db::name('driver')->where('user_id', $groupInfo['driver_user_id'])->find();
                if ($groupTravel && empty($group['reverse_id'])) {
                    // 同步住宿派单
                    $insert = [
                        'driver_id' => $driver['id'],
                        'driver_user_id' => $groupInfo['driver_user_id'],
                        'number_of_guests' => count($groupTravel),
                        'departure_date' => $groupInfo['go_date'],
                        'finish_date' => $groupInfo['end_date'],
                        'group_id' => $group_id,
                        'car_form' => $groupInfo['car_form'],
                        'create_time' => time(),
                    ];
                    // 添加到表里
                    $addId = Db::name('portion_traveler')->strict(false)->insertGetId($insert);

                    //获取订单ids
                    $order_ids = Db::name('order_traveler')->group('oid')->where('group_id', $group_id)->field('id,oid,group_id')->select();

                    //更改订单状态
                    if (count($order_ids) > 1) {
                        // order_status issue已出单
                        // dispose_status normal_travel:正常出行
                        $update['order_status'] = 'issue';
                        $update['dispose_status'] = 'normal_travel';
                        foreach ($order_ids as $ok => $ov) {
                            Db::name('order')->strict(false)->where('id', $ov['oid'])->update($update);
                        }
                    }

                    logs('paidan', $addId);
                }
                return ajax_return_adv('接单成功');
            } else {
                return ajax_return_error('不存在或未填写信息');
            }
        } else {  //如果是接机订单
            //接机单不需要同步住宿
            return ajax_return_adv('接单成功');
        }
    }
    /**
     * 车调待确认订单
     * @return mixed
     */
    public function vehicle_handling()
    {

        $data = input();
        if ($data['sales_id']) {
            $map['o.sales_id'] =array('in',$data['sales_id']) ;
        }
        if($this->request->param("order_id")){
            $map['o.order_id']=array('like',"%{$this->request->param("order_id")}%");
        }
        if ($data['remark']){//新增备注搜索
            $map['ot.remark'] = ['like','%'.$data['remark'].'%'];
        }
        if($data['booking_people_name']){
            $map['o.booking_people_name'] =array('like',"%{$data['booking_people_name']}%") ;
        }
        if($data['booking_people_phone']){
            $map['o.booking_people_phone'] =array('like',"%{$data['booking_people_phone']}%") ;
        }

        if($this->request->param("name")){
            $map['ot.name']=array('like',"%{$this->request->param("name")}%");
        }

        if($this->request->param("phone")){
            $map['ot.phone']=array('like',"%{$this->request->param("phone")}%");
        }
        if($this->request->param("id_card")){
            $map['ot.id_card']=array('like',"%{$this->request->param("id_card")}%");
        }
        if ($data['sku_id']) {
            $map['o.sku_id'] =array('in',$data['sku_id']) ;
        }
        if($data['order_status']){
            $map['o.order_status'] =$data['order_status'];
        }
        if($data['isrefund']=='0'||$data['isrefund']){
            $map['o.isrefund'] = $data['isrefund'];
        }
        if($data['platform']){
            $map['o.platform'] = $data['platform'];
        }
        $map['ot.group_id']=array('gt',0);
        if ($data['date1']) {
            $date1 = strtotime($data['date1']);
        }
        if ($data['date2']) {
            $date2 =  strtotime($data['date2']);
        }

        if ($date1 && $date2) {
            if ($date1 < $date2) {
                $start = $date1;
                $end = $date2;
            } else {
                $start = $date2;
                $end = $date1;
            }
        } else if ($date1) {
            $start = $date1;
        } else if ($date2) {
            $start = $date2;
        }
        if ($start && $end) {
            $map['o.start_time'] = array('between',array($start,$end));
            $this->request->get(array("date1" => date("Y-m-d", $start)));
            $this->request->get(array("date2" => date("Y-m-d", $end)));
        } else if($start){
//            $map['o.start_time'] = array("egt",$start);
            $map['o.start_time'] = array("between",[strtotime($data['start_time']." 00:00:00"),strtotime($data['start_time']." 23:59:59")]);
            $this->request->get(array("date1" => date("Y-m-d", $start)));
        }
        if($data['ctime']){
            $map['o.ctime'] = array("between",[strtotime($data['ctime']." 00:00:00"),strtotime($data['ctime']." 23:59:59")]);

        }

        $listRows = $this->request->param('numPerPage') ?: config("paginate.list_rows");
//        $map['group_id']=0;
        //获取所有需要字段
        $list = Db::name('OrderTraveler')
            ->alias("ot")
            ->join("order o","ot.oid=o.id",'left')
            ->where('ot.vehicle_adjustment','Pending disposal')
            ->where($map)
            ->order('ot.oid desc')
            ->paginate($listRows, false, ['query' => $this->request->get()]);
        //获取订单id
        $oids=[];
        foreach ($list as $item){
            $oids[$item['oid']]=true;
        }
        $oids=array_keys($oids);
        $order_travelers=[];
        //显示字段
        foreach ($oids as $oid){
            $travelers=Db::name('OrderTraveler')
                ->alias("ot")
                ->join("tp_order o","ot.oid=o.id",'left')
                ->join("tp_mfw_sku sku" ,"o.sku_id=sku.sku_id","left")
//                ->join("tp_route r","r.id=o.route_id",'left')
                ->where('oid',$oid)
                ->where('ot.vehicle_adjustment','Pending disposal')
                ->order('ot.oid desc')
                ->field("ot.*,o.title,o.start_time,o.car_form,o.booking_people_name,o.booking_people_phone,o.sales_id,o.order_id,sku.sku_name")
                ->select();
            $num = count($travelers);
            if($num==1){
                $travelers[0]['show_single']=true;
                $travelers[0]['show_mian']=false;
                $travelers[0]['show_between']=false;
                $travelers[0]['show_end']=false;
                $order_travelers[]=$travelers[0];
            }else{
                foreach ($travelers as $key=>$traveler){
                    if($key==0){
                        $travelers[$key]['show_single']=false;
                        $travelers[$key]['show_mian']=true;
                        $travelers[$key]['show_between']=false;
                        $travelers[$key]['show_end']=false;
                    }elseif($key+1<$num){
                        $travelers[$key]['show_single']=false;
                        $travelers[$key]['show_mian']=false;
                        $travelers[$key]['show_between']=true;
                        $travelers[$key]['show_end']=false;
                    }elseif($key+1==$num){
                        $travelers[$key]['show_single']=false;
                        $travelers[$key]['show_mian']=false;
                        $travelers[$key]['show_between']=false;
                        $travelers[$key]['show_end']=true;
                    }
                    $order_travelers[]=$travelers[$key];
                }
            }

        }

//        dump($order_travelers);
        // 模板赋值显示
        $this->view->assign('list', $order_travelers);
        $this->view->assign("count", $list->total());
        $this->view->assign("page", $list->render());
        $this->view->assign('numPerPage', $list->listRows());


        return $this->view->fetch();
    }

    /**
     * 房调待确认订单
     * @return mixed
     */
    public function room_handling()
    {

        $data = input();
        if ($data['sales_id']) {
            $map['o.sales_id'] =array('in',$data['sales_id']) ;
        }
        if($this->request->param("order_id")){
            $map['o.order_id']=array('like',"%{$this->request->param("order_id")}%");
        }
        if ($data['remark']){//新增备注搜索
            $map['ot.remark'] = ['like','%'.$data['remark'].'%'];
        }
        if($data['booking_people_name']){
            $map['o.booking_people_name'] =array('like',"%{$data['booking_people_name']}%") ;
        }
        if($data['booking_people_phone']){
            $map['o.booking_people_phone'] =array('like',"%{$data['booking_people_phone']}%") ;
        }

        if($this->request->param("name")){
            $map['ot.name']=array('like',"%{$this->request->param("name")}%");
        }

        if($this->request->param("phone")){
            $map['ot.phone']=array('like',"%{$this->request->param("phone")}%");
        }
        if($this->request->param("id_card")){
            $map['ot.id_card']=array('like',"%{$this->request->param("id_card")}%");
        }
        if ($data['sku_id']) {
            $map['o.sku_id'] =array('in',$data['sku_id']) ;
        }
        if($data['order_status']){
            $map['o.order_status'] =$data['order_status'];
        }
        if($data['isrefund']=='0'||$data['isrefund']){
            $map['o.isrefund'] = $data['isrefund'];
        }
        if($data['platform']){
            $map['o.platform'] = $data['platform'];
        }
        $map['ot.group_id']=array('gt',0);
        if ($data['date1']) {
            $date1 = strtotime($data['date1']);
        }
        if ($data['date2']) {
            $date2 =  strtotime($data['date2']);
        }
        if ($date1 && $date2) {
            if ($date1 < $date2) {
                $start = $date1;
                $end = $date2;
            } else {
                $start = $date2;
                $end = $date1;
            }
        } else if ($date1) {
            $start = $date1;
        } else if ($date2) {
            $start = $date2;
        }
        if ($start && $end) {
            $map['o.start_time'] = array('between',array($start,$end));
            $this->request->get(array("date1" => date("Y-m-d", $start)));
            $this->request->get(array("date2" => date("Y-m-d", $end)));
        } else if($start){
//            $map['o.start_time'] = array("egt",$start);
            $map['o.start_time'] = array("between",[strtotime($data['start_time']." 00:00:00"),strtotime($data['start_time']." 23:59:59")]);
            $this->request->get(array("date1" => date("Y-m-d", $start)));
        }
        if($data['ctime']){
            $map['o.ctime'] = array("between",[strtotime($data['ctime']." 00:00:00"),strtotime($data['ctime']." 23:59:59")]);

        }

        $listRows = $this->request->param('numPerPage') ?: config("paginate.list_rows");
//        $map['group_id']=0;
         //获取所有需要字段
        $list = Db::name('OrderTraveler')
            ->alias("ot")
            ->join("order o","ot.oid=o.id",'left')
            ->where('ot.room_adjustment','Pending disposal')
            ->where($map)
            ->order('ot.oid desc')
            ->paginate($listRows, false, ['query' => $this->request->get()]);
        //获取订单id
        $oids=[];
        foreach ($list as $item){
            $oids[$item['oid']]=true;
        }
        $oids=array_keys($oids);
        $order_travelers=[];
        //显示字段
        foreach ($oids as $oid){
            $travelers=Db::name('OrderTraveler')
                ->alias("ot")
                ->join("tp_order o","ot.oid=o.id",'left')
                ->join("tp_mfw_sku sku" ,"o.sku_id=sku.sku_id","left")
//                ->join("tp_route r","r.id=o.route_id",'left')
                ->where('oid',$oid)
                ->where('ot.room_adjustment','Pending disposal')
                ->order('ot.oid desc')
                ->field("ot.*,o.title,o.start_time,o.car_form,o.booking_people_name,o.booking_people_phone,o.sales_id,o.order_id,sku.sku_name")
                ->select();
            $num = count($travelers);
            if($num==1){
                $travelers[0]['show_single']=true;
                $travelers[0]['show_mian']=false;
                $travelers[0]['show_between']=false;
                $travelers[0]['show_end']=false;
                $order_travelers[]=$travelers[0];
            }else{
                foreach ($travelers as $key=>$traveler){
                    if($key==0){
                        $travelers[$key]['show_single']=false;
                        $travelers[$key]['show_mian']=true;
                        $travelers[$key]['show_between']=false;
                        $travelers[$key]['show_end']=false;
                    }elseif($key+1<$num){
                        $travelers[$key]['show_single']=false;
                        $travelers[$key]['show_mian']=false;
                        $travelers[$key]['show_between']=true;
                        $travelers[$key]['show_end']=false;
                    }elseif($key+1==$num){
                        $travelers[$key]['show_single']=false;
                        $travelers[$key]['show_mian']=false;
                        $travelers[$key]['show_between']=false;
                        $travelers[$key]['show_end']=true;
                    }
                    $order_travelers[]=$travelers[$key];
                }
            }

        }

//        dump($order_travelers);
        // 模板赋值显示
        $this->view->assign('list', $order_travelers);
        $this->view->assign("count", $list->total());
        $this->view->assign("page", $list->render());
        $this->view->assign('numPerPage', $list->listRows());


        return $this->view->fetch();
    }

    //备份index
    public function index_beifen()
    {

        $data = input();
        $url = '/admin/order_traveler/index_html';
        if ($data){
            foreach ($data as $dk=>$dv){
                if ($dk == $url){
                    unset($data[$dk]);
                }
                if (!empty($dv)){
                    $searchData[$dk] = $dv;
                }
            }
            $searchData['search'] = 'all';
        }else{
            $searchData['search'] = 'all';
        }

        if ($data['sales_id']) {
            $map['o.sales_id'] =array('in',$data['sales_id']) ;
        }
        if($this->request->param("order_id")){
            $map['o.order_id']=array('like',"%{$this->request->param("order_id")}%");
        }
        if($data['booking_people_name']){
            $map['o.booking_people_name'] =array('like',"%{$data['booking_people_name']}%") ;
        }
        if($data['booking_people_phone']){
            $map['o.booking_people_phone'] =array('like',"%{$data['booking_people_phone']}%") ;
        }

        if($this->request->param("name")){
            $map['ot.name']=array('like',"%{$this->request->param("name")}%");
        }

        if($this->request->param("phone")){
            $map['ot.phone']=array('like',"%{$this->request->param("phone")}%");
        }
        if($this->request->param("id_card")){
            $map['ot.id_card']=array('like',"%{$this->request->param("id_card")}%");
        }
        if ($data['sku_id']) {
            $map['o.sku_id'] =array('in',$data['sku_id']) ;
        }
        if($data['order_status']){
            $map['o.order_status'] =$data['order_status'];
        }
        if($data['isrefund']=='0'||$data['isrefund']){
            $map['o.isrefund'] = $data['isrefund'];
        }
        if($data['platform']){
            $map['o.platform'] = $data['platform'];
        }
        if ($this->request->param("isallot")) {
            $map['ot.group_id']=array('gt',0);
        }elseif ($this->request->param("isallot")==="0"){
            $map['ot.group_id']=0;
        }
//        if ($data['date1']) {
//            $date1 = strtotime($data['date1']);
//        }
//        if ($data['date2']) {
//            $date2 =  strtotime($data['date2']);
//        }
//
//        if ($date1 && $date2) {
//            if ($date1 < $date2) {
//                $start = $date1;
//                $end = $date2;
//            } else {
//                $start = $date2;
//                $end = $date1;
//            }
//        } else if ($date1) {
//            $start = $date1;
//        } else if ($date2) {
//            $start = $date2;
//        }
//        if ($start && $end) {
//            $map['o.start_time'] = array('between',array($start,$end));
//            $this->request->get(array("date1" => date("Y-m-d", $start)));
//            $this->request->get(array("date2" => date("Y-m-d", $end)));
//        } else if($start){
////            $map['o.start_time'] = array("egt",$start);
//            $map['o.start_time'] = array("between",[strtotime($data['start_time']." 00:00:00"),strtotime($data['start_time']." 23:59:59")]);
//            $this->request->get(array("date1" => date("Y-m-d", $start)));
//        }
        if($data['ctime']){
            $map['o.ctime'] = array("between",[strtotime($data['ctime']." 00:00:00"),strtotime($data['ctime']." 23:59:59")]);

        }

        //出行日期
        if ($data['start_time']){
            $map['o.start_time'] = ['=',strtotime($data['start_time'])];
        }


        $listRows = $this->request->param('numPerPage') ?: config("paginate.list_rows");
//        $map['group_id']=0;
        $list = Db::name('OrderTraveler')
            ->alias("ot")
            ->join("order o","ot.oid=o.id",'left')
            ->where($map)
            ->order('ot.oid desc')
            ->paginate($listRows, false, ['query' => $this->request->get()]);

        //获取订单id
        $oids=[];
        foreach ($list as $item){
            $oids[$item['oid']]=true;
        }
        $oids=array_keys($oids);
        $order_travelers=[];
        foreach ($oids as $oid){
            $travelers=Db::name('OrderTraveler')
                ->alias("ot")
                ->join("tp_order o","ot.oid=o.id",'left')
                ->join("tp_mfw_sku sku" ,"o.sku_id=sku.sku_id","left")
//                ->join("tp_route r","r.id=o.route_id",'left')
                ->where('oid',$oid)
                ->order('ot.oid desc')
                ->field("ot.*,o.title,o.start_time,o.car_form,o.booking_people_name,o.booking_people_phone,o.sales_id,o.order_id,sku.sku_name")
                ->select();
            $num = count($travelers);
            if($num==1){
                $travelers[0]['show_single']=true;
                $travelers[0]['show_mian']=false;
                $travelers[0]['show_between']=false;
                $travelers[0]['show_end']=false;
                $order_travelers[]=$travelers[0];
            }else{
                foreach ($travelers as $key=>$traveler){
                    if($key==0){
                        $travelers[$key]['show_single']=false;
                        $travelers[$key]['show_mian']=true;
                        $travelers[$key]['show_between']=false;
                        $travelers[$key]['show_end']=false;
                    }elseif($key+1<$num){
                        $travelers[$key]['show_single']=false;
                        $travelers[$key]['show_mian']=false;
                        $travelers[$key]['show_between']=true;
                        $travelers[$key]['show_end']=false;
                    }elseif($key+1==$num){
                        $travelers[$key]['show_single']=false;
                        $travelers[$key]['show_mian']=false;
                        $travelers[$key]['show_between']=false;
                        $travelers[$key]['show_end']=true;
                    }
                    $order_travelers[]=$travelers[$key];
                }
            }

        }

        // 模板赋值显示
        $this->view->assign('list', $order_travelers);
        $this->view->assign("count", $list->total());
        $this->view->assign("page", $list->render());
        $this->view->assign('numPerPage', $list->listRows());
        $this->view->assign('searchCondition',$searchData);//搜索条件


        return $this->view->fetch();
    }





    // 备份
    public function driver01()
    {
        $input=input();
        echo '<br><br><br><br><br><br><br>';
        dump($input);
        $group_id=$input['group_id'];
        $order_id = $input['order_id'];
        if(!$this->request->isAjax()){
            //查询该订单信息
            $order = Db::name('order')->where('id',$input['order_id'])->field('id,order_id,start_time')->find();
            // 过滤掉已选择的司机
            $driver_user_id = explode(',',$input['driver_user_id']);
            $selectUserIds = '';
            if ($driver_user_id){
                foreach ($driver_user_id as $duk=>$duv){
                    if (!empty($duv)){
                        $selectUserIds .= $duv.',';//要过滤掉的用户id
                    }
                }
                if ($selectUserIds){
                    $map['d.user_id'] = ['not in',$selectUserIds];
                }
            }
            if($input['realname']){
                $map['u.realname']=array('like',"%{$input['realname']}%");
            }
            if($input['mobile']){
                $map['u.account']=array('like',"%{$input['mobile']}%");
            }
            if($input['seats']){
                $map['d.seats']=$input['seats'];
            }
            if($input['car_type']){
                $map['d.car_type']=array('like',"%{$input['car_type']}%");
            }
            if($input['car_model']){
                $map['d.car_model']=array('like',"%{$input['car_model']}%");
            }
            if($input['car_brand']){
                $map['d.car_brand']=array('like',"%{$input['car_brand']}%");
            }
            if($input['driver_rank_id']){
                if ($input['driver_rank_id'] == 5){
                    $map['d.driver_rank_id']=0;
                }else{
                    $map['d.driver_rank_id']=$input['driver_rank_id'];
                }
            }
            if ($input['nationality']){
                $map['d.nationality'] = ['like', "%{$input['nationality']}%"];
            }
            if($input['tag']){
                $map['d.tag']=array('like',"%{$input['tag']}%");
            }
            $map['d.inservice']=false;
            $group=Db::name('dispatch_traveler_group')->where(array('id'=>$group_id))->find();
            //查找不在服务状态的司机，也没有订单
            $driver_users=Db::name('driver')->alias('d')
                ->join('tp_admin_user u','u.id=d.user_id','left')
                ->join("tp_driver_rank r", "r.id=d.driver_rank_id", "left")
                ->where('isagree',1)
                ->where($map)
                ->order('d.id','desc')
                ->field("u.*,d.*,r.name as r_name,d.nationality")
                ->select();
            //查找派单和进行的订单量<2的司机
            $sendOrder = Db::name('dispatch_traveler_group')
                ->where('dispatch_group_status','in',['proceed','sendorders'])
                ->field('id,driver_user_id')
                ->select();
            $userIds = '';
            if ($sendOrder){
                $arr = [];
                foreach ($sendOrder as $sok=>$sov){
                    $arr[$sov['driver_user_id']][] = $sov['id'];
                }
                if ($arr){
                    foreach ($arr as $ak=>$av){
                        if (count($av) >= 2){
                            $userIds .= $ak.',';
                        }
                    }
                }
                $userIds = explode(',',rtrim($userIds,','));//就是派单和进行大于等于2的司机
            }
            unset($map['d.user_id']);
            unset($map['d.inservice']);
            //查只有一个单的派单或进行的司机
            $driverData = Db::name('dispatch_traveler_group')->where('dispatch_group_status','in',['proceed','sendorders'])
                ->where('driver_user_id','not in',$userIds)->field('driver_user_id')
                ->select();
            $ids ='';
            if ($driverData){
                foreach ($driverData  as $dk=>$dv){
                    $ids .= $dv['driver_user_id'].',';
                }
                $ids = explode(',',$ids);
            }
            //查找只有一个单的司机
            $drivers_in_service=Db::name('driver')->alias('d')
                ->join('tp_admin_user u','u.id=d.user_id','left')
                ->join("tp_driver_rank r", "r.id=d.driver_rank_id", "left")
                ->where('d.isagree',1)
                ->where('d.user_id','in',$ids)
                ->where($map)
                ->order('d.id','desc')
                ->field("u.*,d.*,r.name as r_name,d.nationality")
                ->select();
            //过滤司机签一单结束时间大于分配订单的开始时间
            foreach ($drivers_in_service as $disk=>$disv){
                $driverService = Db::name('dispatch_traveler_group')->where('driver_user_id',$disv['user_id'])
                    ->where('dispatch_group_status','in',['proceed','sendorders'])
                    ->order('id','desc')->select();
                $driverServiceInfo = $driverService[0];
                if (!$driverServiceInfo['end_date']){ // 取消结束时间为空
                    unset($drivers_in_service[$disk]);
                }elseif ($driverServiceInfo['end_date'] > $order['start_time']){//去掉结束时间大于开始时间
                    unset($drivers_in_service[$disk]);
                }
            }
            $this->view->assign("driver_users",$driver_users);
            $this->view->assign("group_id",$group_id);
            $this->view->assign("order_id",$order_id);
            $this->view->assign("drivers_in_service",$drivers_in_service);
            $this->view->assign('vo',$group);
            $map_tags['isdelete']=0;
            $map_tags['status']=1;
            $driver_tags=Db::name('driver_tag')
                ->where($map_tags)
                ->select();
            $this->view->assign('driver_tags',$driver_tags);


            $ranks=Db::name('driver_rank')->select();
            $this->view->assign('ranks',$ranks);
            return $this->view->fetch();
        }
        //判断订单是否异常
        $group_order_ids=Db::name('dispatch_traveler')

            ->where('group_id',$group_id)
            ->column("oid");
        if (!input('driver_user_id')){
            return ajax_return_adv_error('没有选择司机');
        }
        $exceptional_orders= Db::name('exceptional_order')->where('oid','in',$group_order_ids)->where('solve',false)->find();
        if($exceptional_orders){
            return ajax_return_error("订单id为{$exceptional_orders['oid']}的订单存在异常状态");
        }
        $dispatch_traveler_group=Db::name('dispatch_traveler_group')->where('id',$group_id)->find();

        //判断司机是否已经在服务
        $driver=Db::name("driver")->where('user_id',$dispatch_traveler_group['driver_user_id'])->find();
        if($driver['inservice']){
            return ajax_return_error("用户id为{$dispatch_traveler_group['driver_user_id']}的司机已经分配");
        }
        if($dispatch_traveler_group['dispatch_group_status']=='undistributed'||!$dispatch_traveler_group['dispatch_group_status']) {
            $update=input();
            $update['dispatch_group_status']='sendorders';
            $update['driver_confirm']=false;
            $update['isreject']=false;
            $update['dispatch_time']=NOW_TIME;
            Db::name('dispatch_traveler_group')->where('id',$group_id)->update($update);
            Db::name("driver")->where('user_id',$dispatch_traveler_group['driver_user_id'])->update(array('inservice'=>1));
            if ($update['driver_user_id']) {
                $map['user_id'] = $update['driver_user_id'];
                $map['type'] = "dispatch_traveler_group";
                $map['dispatch_traveler_group_id'] = $group_id;

                set_info($dispatch_traveler_group['driver_user_id'], '订单分配', '分配成功，你有新的订单', 'dispatch_traveler_group', array('dispatch_traveler_group_id' => $group_id));

                return ajax_return_adv('操作成功');

            }else{

                return ajax_return_error('未分配司导');
            }
        }else{
            return ajax_return_error('已经分配');
        }
    }

}
